from odoo import api, models, fields, _
from odoo.exceptions import ValidationError
import logging
import json
_logger = logging.getLogger(__name__)


class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'

    s_service_pricing_method = fields.Selection([('panel', 'Panel'), ('area', 'Area'), ('nothing', 'Normal')],
                                                string='Subcontracting Pricing Method')
    sb_subcontracting_apply_id = fields.Many2one('sb.subcontracting.apply')
    is_all_outside = fields.Boolean(related='sb_subcontracting_apply_id.is_all_outside', help='包工包料/多工序外发')

    def cron_sub_outside(self):
        """修复数据使用"""
        order_line_ids = [(0, 0, {'purchase_line_id': l.id}) for l in self.order_line]
        self.env['stock.subcon.outside'].sudo().create({
            'purchase_id': self.id,
            'line_ids': order_line_ids,
        })

    def button_cancel(self):
        res = super(PurchaseOrder, self).button_cancel()
        if self.subcon_in:
            raise ValidationError(_('外发PO已接收，无法取消。'))
        return res


class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    def _compute_s_subcontracting_json(self):
        for record in self:
            try:
                if record.sb_subcontracting_apply_line_id.workorder_id.note_sb:
                    note_sb = record.sb_subcontracting_apply_line_id.workorder_id.note_sb
                    s_subcontracting_json = dict([(str(i), json.loads(n)) for i, n in enumerate(note_sb.split(' - '))])
                    record.s_subcontracting_json = s_subcontracting_json
                else:
                    record.s_subcontracting_json = {}
            except Exception as e:
                print(e)
                record.s_subcontracting_json = {}

    s_production_id = fields.Many2one('mrp.production', string='Production', copy=False, readonly=True)
    s_subcontracting_product_id = fields.Many2one('product.product', string='Subcontracting Product', copy=False,
                                                  readonly=True)
    s_specs = fields.Char('Specs', copy=False, readonly=True, tracking=True)
    # 每pnl平米价格
    area_price_unit = fields.Float('Area Price Unit', digits="Product Unit of Measure", tracking=True)
    # Pcs 数
    qty_wip_pcs = fields.Float(string='Pcs')
    # 单pnl有效平米数
    area_pnl_qty = fields.Float(string='Active PANEL/M²', digits="Product Unit of Measure", tracking=True)
    sb_subcontracting_apply_line_id = fields.Many2one('sb.subcontracting.apply.line')
    s_subcontracting_json = fields.Json(string="外发接收数量", compute='_compute_s_subcontracting_json')

    @api.onchange('area_price_unit', 'area_pnl_qty')
    def onchange_unit_price(self):
        self.price_unit = self.area_price_unit * self.area_pnl_qty

    def write(self, vals):
        if 'area_price_unit' in vals:
            new_area_price = vals['area_price_unit']
            old_area_price = self.area_price_unit
            vals['area_price_unit'] = round(new_area_price, 3)
        if 'area_pnl_qty' in vals:
            new_pnl_area = vals['area_pnl_qty']
            old_pnl_area = self.area_pnl_qty
            vals['area_pnl_qty'] = round(new_pnl_area, 3)
        res = super(PurchaseOrderLine, self).write(vals)
        if 'old_area_price' in locals():
            new_area_price = self.area_price_unit
            body = "单价: {} --> {}".format(old_area_price, round(new_area_price, 3))
            self.order_id.message_post(body=body)
        if 'old_pnl_area' in locals():
            new_pnl_area = self.area_pnl_qty
            body = "有效面积: {} --> {}".format(old_pnl_area, round(new_pnl_area, 3))
            self.order_id.message_post(body=body)
        return res
